package com.irishud.hudnavi.udp;

import android.os.ConditionVariable;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/10/1.
 */
public class UdpTxThread {
    String TAG = "UdpTxThread";

    String ip;
    InetAddress inetAddress;
    int    port;
    Thread thread;
    DatagramSocket socket;
    DatagramPacket packet;

    List<ByteBuffer> buffQueue = new ArrayList<>();
    ConditionVariable lock = new ConditionVariable(false);

    boolean isRunning = true;

    public UdpTxThread(String ipAddr, final int port){
        this.ip = ipAddr;
        this.port = port;
        try {
            inetAddress = InetAddress.getByName(ipAddr);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new DatagramSocket(port);
                    socket.setReuseAddress(true);
                    while(isRunning){
                        Log.i(TAG,"---------------------> UdpTxThread send queueSize:"+buffQueue.size());
                        if(buffQueue.size() > 0){
                            ByteBuffer byteBuffer = buffQueue.get(0);
                            packet =new DatagramPacket(byteBuffer.array(),
                                    byteBuffer.array().length,inetAddress,port);
                            socket.send(packet);
                            buffQueue.remove(0);
                        }else{
                            lock.close();
                            lock.block();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG,"udp error:" +e.getMessage());
                }
            }
        });
        thread.start();
        Log.e(TAG,"---------------------> UdpTxThread stared!");
    }

    public void stop(){
        isRunning = false;
        thread.interrupt();
    }

    public void enqueue(ByteBuffer buffer){
        buffQueue.add(buffer);
        lock.open();
    }
}
